
package session.stateless;

import entity.Position;
import entity.Role;
import java.util.Collection;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class PositionSessionBean implements PositionSessionBeanLocal {
    @PersistenceContext 
    private EntityManager entityManager; 

    public String getPositionDescription(Long positionId){
        Position position =entityManager.find(Position.class, positionId);
        return position.getDescription();
    } 
    
    public List<Position> getPositions(){
        Query q = entityManager.createQuery("SELECT p FROM Position p");
                      
        return q.getResultList();    
    }
    
    public List<Role> getRoles(Long positionId)
    {
        Position position = entityManager.find(Position.class, positionId);
        
        return (List<Role>) position.getRoles();
        
    }
    
    @Override
    public long createPosition(String description, List<Role> role) {
        System.out.println("test before create"+description+"   "+role.size());
        Position position = new Position();
        System.out.println("Position after create"+position.getId());
        position.setDescription(description);
        position.setRoles(role);
        
        entityManager.persist(position);   
        System.out.println("after create"+position.getRoles().size());
        return position.getId();
    }    
    
    @Override
    public void updatePosition(Long positionId, String positionDescription, List<Role> positionRoles){
        Position position = entityManager.find(Position.class, positionId);       
        if (position ==null)
             System.out.println("Position does not exist. Please try again.");
        else
        {
            position.setDescription(positionDescription);
            position.setRoles(positionRoles);
            entityManager.flush();
        }
    }
    
    @Override
    public void deletePosition(Long positionId){
        Position position = entityManager.find(Position.class, positionId);
        if (position == null) 
            System.out.println("Hi!");
            //throw new ExistException("Sale Lead does not exist.");
        else
        {
            //Remove all dependencies before deleting
            entityManager.remove(position);
        }
    }

    @Override
    public long getPosition(String positionDescription) {
        Query query=entityManager.createQuery("SELECT p FROM Position p WHERE p.description =:positionDescription");
        query.setParameter("positionDescription", positionDescription);
        
        Position temp = (Position) query.getSingleResult();
        return temp.getId();
        
    }
}
